package esb.chapter4.component;

import javax.annotation.Resource;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.xml.transform.Source;

import org.apache.log4j.Logger;
import org.apache.servicemix.MessageExchangeListener;
import org.apache.servicemix.components.util.ComponentSupport;
import org.apache.servicemix.jbi.jaxp.SourceTransformer;
import org.w3c.dom.Element;

public class SimpleSpringComponent extends ComponentSupport implements MessageExchangeListener {
	
	private final static Logger logger = Logger.getLogger(SimpleSpringComponent.class);
	private SourceTransformer sourceTransformer = new SourceTransformer();
	@Resource
	private DeliveryChannel channel;
	private ResponseOptionsIF responseOptions;
	
    public void onMessageExchange(MessageExchange exchange) throws MessagingException {
    	Element payloadElem = null;
    	try {
    		Source contentSource = getInMessage(exchange).getContent();
    		payloadElem = sourceTransformer.toDOMElement(contentSource);
        } catch(Exception e) {
        	logger.error("error while reading payload", e);
        }
        String word = payloadElem.getTextContent();
        String response = responseOptions.getResponseOption(word);
        logger.info("for word " + word + " response is " + response);
        exchange.setStatus(ExchangeStatus.DONE);
        channel.send(exchange);        
    }
    
    public void setResponseOptions(ResponseOptionsIF responseOptions) {
    	this.responseOptions = responseOptions;
    }

}
